<template>
	<div class="warehouse-area-container base-page-container">
		<!-- 搜索区域 -->
		<common-search v-model="searchForm" :search-items="searchItemsConfig" @search="handleSearch"
			@reset="fetchTableData">
		</common-search>

		<!-- 操作按钮区域 -->
		<action-buttons :selected-data="selectedRows" :action-permissions="actionPermissions" add-type="success" :export-type="themeType"
			:import-type="themeType" :enable-type="themeType" :disable-type="themeType" @add="handleAdd"
			@export="handleExport" @import="handleImport" @enable="handleEnable" @disable="handleDisable" />

		<!-- 表格区域 -->
		<custom-table
			:data="tableData"
			:columns="tableColumns"
			:loading="tableLoading"
			:current-page="pagination.currentPage"
			:page-size="pagination.pageSize"
			:total="pagination.total"
			table-id="warehouse-area-table"
			@selection-change="handleSelectionChange"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		>
			<!-- 库区类型列的自定义插槽 -->
			<template #areaType="{ row }">
				<el-tag :type="getAreaTypeTagType(row.areaType)">
					{{ row.areaType }}
				</el-tag>
			</template>
			
			<!-- 操作列 -->
			<template #operation="{ row }">
				<theme-button v-if="tablePermissions.edit" link @click="handleEdit(row)">编辑</theme-button>
				<theme-button v-if="tablePermissions.view" link @click="handleView(row)">查看</theme-button>
				<theme-button v-if="tablePermissions.log" link @click="handleLog(row)">日志</theme-button>
			</template>
		</custom-table>	

		<!-- 库区信息弹窗 -->
		<el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增库区' : '编辑库区'" width="750px"
			destroy-on-close class="base-dialog" :close-on-click-modal="false">
			<el-form ref="areaFormRef" :model="areaForm" :rules="areaFormRules" label-width="80px"
				class="base-form">
				<div class="form-row">
					<el-form-item label="库区编号" prop="code" required>
						<el-input v-model="areaForm.code" placeholder="请输入库区编号"></el-input>
					</el-form-item>
					<el-form-item label="库区名称" prop="name" required>
						<el-input v-model="areaForm.name" placeholder="请输入库区名称"></el-input>
					</el-form-item>
				</div>

				<div class="form-row">
					<el-form-item label="库区类型" prop="areaType" required>
						<el-select v-model="areaForm.areaType" placeholder="请选择库区类型" style="width: 100%">
							<el-option label="存储区" value="存储区"></el-option>
							<el-option label="拣货区" value="拣货区"></el-option>
							<el-option label="暂存区" value="暂存区"></el-option>
							<el-option label="次品区" value="次品区"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="面积(m²)" prop="area">
						<el-input v-model.number="areaForm.area" placeholder="请输入面积" type="number"></el-input>
					</el-form-item>
				</div>

				<div class="form-row" style="width: 48%">
					<el-form-item label="体积(m³)" prop="capacity">
						<el-input v-model.number="areaForm.capacity" placeholder="请输入体积" type="number"></el-input>
					</el-form-item>
				</div>

				<div class="form-row full-width" >
					<el-form-item label="下辖通道" class="full-width-item">
						<div class="channel-container">
							<!-- <div class="channel-footer">
								<el-button type="primary" size="small" @click="addChannel">
									<el-icon><Plus /></el-icon> 添加通道
								</el-button>
							</div> -->
							<div class="channel-header">
								<div class="header-item">#</div>
								<div class="header-item">通道名称</div>
								<div class="header-item">行</div>
								<div class="header-item">单双列</div>
								<div class="header-item">最大货位数</div>
								<div class="header-item" @click="addChannel">
									<el-icon><CirclePlus /></el-icon>
								</div>
							</div>
							<div class="channel-body">
								<div v-for="(channel, index) in areaForm.channels" :key="index" class="channel-row">
									<div class="body-item">{{ index + 1 }}</div>
									<div class="body-item">
										<el-input v-model="channel.name" placeholder="通道名称"></el-input>
									</div>
									<div class="body-item">
										<el-input v-model.number="channel.rowCount" placeholder="行" type="number"></el-input>
									</div>
									<div class="body-item">
										<el-select v-model="channel.columnType" placeholder="单双列">
											<el-option label="单列" value="单列"></el-option>
											<el-option label="双列" value="双列"></el-option>
											<el-option label="多列" value="多列"></el-option>
										</el-select>
									</div>
									<div class="body-item">
										<el-input v-model.number="channel.maxLocations" placeholder="最大货位数" type="number"></el-input>
									</div>
									<div class="body-item">
										<el-button type="danger" circle size="small" @click="removeChannel(index)">
											<el-icon><Delete /></el-icon>
										</el-button>
									</div>
								</div>
							</div>
						</div>
					</el-form-item>
				</div>

			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitForm">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 日志弹窗 -->
		<log-dialog
			v-model:visible="logDialogVisible"
			:log-data="logData"
			:total="logPagination.total"
			:current-page="logPagination.currentPage"
			:page-size="logPagination.pageSize"
			@size-change="handleLogSizeChange"
			@current-change="handleLogCurrentChange"
		/>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed
	} from 'vue'
	import {
		useTheme
	} from '@/hooks/useTheme'
	import {
		RegionCascader
	} from '@/components/common'
	import { Delete, Plus } from '@element-plus/icons-vue'

	// 使用主题组合API
	const {
		themeType
	} = useTheme()

	// 判断是否开发环境
	const isDevelopment = computed(() => {
		return import.meta.env.MODE === 'development'
	})

	// 搜索项配置列表
	const searchItemsConfig = [{
			label: '库区编号',
			prop: 'code',
			type: 'el-input',
			placeholder: '请输入库区编号',
			defaultVisible: true
		},
		{
			label: '库区名称',
			prop: 'name',
			type: 'el-input',
			placeholder: '请输入库区名称',
			defaultVisible: true
		},
		{
			label: '库区类型',
			prop: 'areaType',
			type: 'el-select',
			placeholder: '请选择库区类型',
			defaultVisible: true,
			multiple: true,
			collapseTags: true,
			collapseTagsTooltip: true,
			options: [
				{
					label: '存储区',
					value: '存储区'
				},
				{
					label: '拣货区',
					value: '拣货区'
				},
				{
					label: '暂存区',
					value: '暂存区'
				},
				{
					label: '次品区',
					value: '次品区'
				}
			]
		},
		// {
		// 	label: '创建日期',
		// 	prop: 'createDate',
		// 	type: 'el-date-picker',
		// 	placeholder: '请选择创建日期',
		// 	defaultVisible: true,
		// 	dateType: 'date',
		// 	format: 'YYYY-MM-DD',
		// 	valueFormat: 'YYYY-MM-DD'
		// }
	]

	// 操作按钮权限
	const actionPermissions = ref({
		add: true,
		export: false,
		import: false,
		enable:false,
		disable:false,
		viewLog:true,
		delete:true
	})

	// 表格操作权限
	const tablePermissions = ref({
		edit: true,
		view: true,
		log: true
	})

	// 搜索表单数据
	const searchForm = reactive({
		code: '',
		name: '',
		areaType: '',
		createDate: ''
	})

	// 表格数据相关
	const tableData = ref([])
	const tableLoading = ref(false)
	const selectedRows = ref([])

	// 分页相关
	const pagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0
	})

	// 获取库区类型对应的标签类型
	const getAreaTypeTagType = (areaType) => {
		switch (areaType) {
			case '存储区':
				return 'success'
			case '拣货区':
				return 'warning'
			case '暂存区':
				return 'info'
			case '次品区':
				return 'danger'
			default:
				return ''
		}
	}

	// 库区表单相关
	const areaFormRef = ref(null)
	const dialogVisible = ref(false)
	const dialogType = ref('add') // 'add' 或 'edit'
	const areaForm = reactive({
		id: '',
		code: '',
		name: '',
		areaType: '存储区',
		area: '',
		capacity: '',
		channels: [],
		remark: ''
	})

	// 添加通道
	const addChannel = () => {
		areaForm.channels.push({
			name: '',
			rowCount: 1,
			columnType: '单列',
			maxLocations: 0
		})
	}

	// 移除通道
	const removeChannel = (index) => {
		areaForm.channels.splice(index, 1)
	}

	// 表单校验规则
	const areaFormRules = {
		code: [{
			required: true,
			message: '请输入库区编号',
			trigger: 'blur'
		}],
		name: [{
			required: true,
			message: '请输入库区名称',
			trigger: 'blur'
		}],
		areaType: [{
			required: true,
			message: '请选择库区类型',
			trigger: 'change'
		}],
		area: [{
			type: 'number',
			message: '面积必须为数字',
			trigger: 'blur'
		}],
		capacity: [{
			type: 'number',
			message: '体积必须为数字',
			trigger: 'blur'
		}]
	}

	// 日志弹窗相关
	const logDialogVisible = ref(false)
	const logData = ref([])
	const logPagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0
	})

	// 表格列配置
	const tableColumns = ref([
		{ prop: 'code', label: '库区编号', width: '100', minWidth: '100', visible: true },
		{ prop: 'name', label: '库区名称', width: '150', minWidth: '150', visible: true },
		{ prop: 'areaType', label: '库区类型', width: '120', minWidth: '120', visible: true },
		{ prop: 'capacity', label: '体积(m³)', width: '100', minWidth: '100', visible: true },
		{ prop: 'area', label: '面积(m²)', width: '100', minWidth: '100', visible: true },
		{ prop: 'channelInfo', label: '通道名称', minWidth: '150', visible: true },
		{ prop: 'createdBy', label: '创建人', width: '100', minWidth: '100', visible: true },
		{ prop: 'createdTime', label: '创建时间', width: '160', minWidth: '160', visible: true },
		{ prop: 'updatedBy', label: '修改人', width: '100', minWidth: '100', visible: true },
		{ prop: 'updatedTime', label: '修改时间', width: '160', minWidth: '160', visible: true },
		{ prop: 'remark', label: '备注', minWidth: '150', visible: false },
		{ prop: 'operation', label: '操作', width: '160', minWidth: '160', fixed: 'right', visible: true }
	])

	// 获取表格数据
	const fetchTableData = async () => {
		tableLoading.value = true

		try {
			// 模拟异步请求
			if (isDevelopment.value) {
				setTimeout(() => {
					// 模拟数据
					tableData.value = [{
							id: '1',
							code: 'A',
							name: '预留区A',
							areaType: '预留区',
							area: 10000,
							capacity: 100,
							channelInfo: '1通道, 2通道, 3通道',
							channels: [
								{ name: '1通道', rowCount: 1, columnType: '单列', maxLocations: 100 },
								{ name: '2通道', rowCount: 2, columnType: '双列', maxLocations: 200 },
								{ name: '3通道', rowCount: 3, columnType: '多列', maxLocations: 300 }
							],
							createdBy: '小李',
							createdTime: '2024-11-02 10:23:10',
							updatedBy: '小李', 
							updatedTime: '2024-11-02 10:23:10',
							remark: ''
						},
						{
							id: '2',
							code: 'D',
							name: '存储区A',
							areaType: '存储区',
							area: 10000,
							capacity: 100,
							channelInfo: '1通道',
							channels: [
								{ name: '1通道', rowCount: 1, columnType: '单列', maxLocations: 100 }
							],
							createdBy: '小李',
							createdTime: '2024-11-01 20:03:27',
							updatedBy: '小李',
							updatedTime: '2024-11-01 20:03:27',
							remark: ''
						},
						{
							id: '3',
							code: 'C',
							name: '暂存区A',
							areaType: '暂存区',
							area: 10000,
							capacity: 100,
							channelInfo: '1通道',
							channels: [
								{ name: '1通道', rowCount: 1, columnType: '单列', maxLocations: 100 }
							],
							createdBy: '小李',
							createdTime: '2024-10-20 17:47:10',
							updatedBy: '小李',
							updatedTime: '2024-10-20 17:47:10',
							remark: ''
						},
						{
							id: '4',
							code: 'B',
							name: '次品区A',
							areaType: '次品区',
							area: 10000,
							capacity: 100,
							channelInfo: '1通道',
							channels: [
								{ name: '1通道', rowCount: 1, columnType: '单列', maxLocations: 100 }
							],
							createdBy: '小李',
							createdTime: '2024-10-20 17:46:17',
							updatedBy: '小李',
							updatedTime: '2024-10-20 17:46:17',
							remark: ''
						},
						{
							id: '5',
							code: 'A',
							name: '拣货区A',
							areaType: '拣货区',
							area: 10000,
							capacity: 100,
							channelInfo: '1通道',
							channels: [
								{ name: '1通道', rowCount: 1, columnType: '单列', maxLocations: 100 }
							],
							createdBy: '小李',
							createdTime: '2024-10-20 17:45:42',
							updatedBy: '小李',
							updatedTime: '2024-10-20 17:45:42',
							remark: ''
						}
					]

					pagination.total = 5 // 模拟总数据量
					tableLoading.value = false
				}, 500)
			} else {
				// 实际环境API调用
				// const res = await api.getWarehouseAreaList({
				//   page: pagination.currentPage,
				//   pageSize: pagination.pageSize,
				//   ...searchForm
				// })
				// tableData.value = res.data.list
				// pagination.total = res.data.total
				tableLoading.value = false
			}
		} catch (error) {
			console.error('获取库区列表失败', error)
			tableLoading.value = false
		}
	}

	// 处理分页大小变化
	const handleSizeChange = (size) => {
		pagination.pageSize = size
		fetchTableData()
	}

	// 处理当前页变化
	const handleCurrentChange = (page) => {
		pagination.currentPage = page
		fetchTableData()
	}

	// 处理表格选择事件
	const handleSelectionChange = (rows) => {
		selectedRows.value = rows
	}

	// 处理搜索
	const handleSearch = () => {
		pagination.currentPage = 1
		// 处理搜索条件，构建API请求参数
		const params = { ...searchForm }
		console.log('搜索参数:', params)
		// 调用获取数据函数
		fetchTableData()
	}

	// 处理添加库区
	const handleAdd = () => {
		dialogType.value = 'add'
		dialogVisible.value = true
		// 清空表单
		Object.keys(areaForm).forEach(key => {
			if (key === 'areaType') {
				areaForm[key] = '存储区'
			} else if (key === 'channels') {
				areaForm[key] = []
			} else {
				areaForm[key] = ''
			}
		})
	}

	// 处理编辑库区
	const handleEdit = (row) => {
		dialogType.value = 'edit'
		dialogVisible.value = true

		// 填充表单数据
		Object.keys(areaForm).forEach(key => {
			areaForm[key] = row[key] || (key === 'channels' ? [] : '')
		})
		
		// 确保channels是数组
		if (!Array.isArray(areaForm.channels) || areaForm.channels.length === 0) {
			areaForm.channels = []
			// 如果没有通道但有通道信息，尝试解析
			if (row.channelInfo) {
				const channelNames = row.channelInfo.split(', ')
				channelNames.forEach(name => {
					areaForm.channels.push({
						name,
						rowCount: 1,
						columnType: '单列',
						maxLocations: 100
					})
				})
			}
		}
	}

	// 处理查看库区
	const handleView = (row) => {
		// 实现查看逻辑...
		console.log('查看库区', row)
	}

	// 处理日志
	const handleLog = (row) => {
		logDialogVisible.value = true

		// 模拟日志数据
		setTimeout(() => {
			logData.value = [{
					operateTime: '2024-01-05 14:30:25',
					operator: '小李',
					operateContent: `修改了库区 ${row.name} 的通道信息`
				},
				{
					operateTime: '2023-12-20 09:15:36',
					operator: '小王',
					operateContent: `修改了库区 ${row.name} 的面积信息`
				},
				{
					operateTime: '2023-11-15 16:42:10',
					operator: '小张',
					operateContent: `创建了库区 ${row.name}`
				}
			]
			logPagination.total = 3
		}, 300)
	}

	// 处理日志分页变化
	const handleLogSizeChange = (size) => {
		logPagination.pageSize = size
		// 重新获取日志数据
	}

	const handleLogCurrentChange = (page) => {
		logPagination.currentPage = page
		// 重新获取日志数据
	}

	// 处理导出
	const handleExport = () => {
		console.log('导出库区数据')
	}

	// 处理导入
	const handleImport = () => {
		console.log('导入库区数据')
	}

	// 处理启用
	const handleEnable = () => {
		if (selectedRows.value.length === 0) {
			ElMessage.warning('请选择要启用的库区')
			return
		}

		console.log('启用库区', selectedRows.value)
	}

	// 处理停用
	const handleDisable = () => {
		if (selectedRows.value.length === 0) {
			ElMessage.warning('请选择要停用的库区')
			return
		}

		console.log('停用库区', selectedRows.value)
	}

	// 提交表单
	const submitForm = async () => {
		areaFormRef.value.validate(async (valid) => {
			if (valid) {
				// 处理表单数据
				const submitData = { ...areaForm }
				
				// 生成通道信息字符串
				const channelInfo = submitData.channels.map(ch => ch.name).join(', ')
				submitData.channelInfo = channelInfo

				console.log('提交表单', submitData)

				try {
					// 模拟提交
					setTimeout(() => {
						ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
						dialogVisible.value = false
						fetchTableData()
					}, 500)
				} catch (error) {
					console.error('提交表单失败', error)
				}
			}
		})
	}

	// 页面初始化
	onMounted(() => {
		fetchTableData()
	})
</script>

<style lang="scss" scoped>
.channel-container {
	margin-top: 5px;
	border: 1px solid #ebeef5;
	border-radius: 4px;
	flex: 1;
	.channel-header {
		flex: 1;
		display: flex;
		align-items: center;
		background-color: #f5f7fa;
		padding: 10px;
		border-bottom: 1px solid #ebeef5;
		font-weight: bold;

		.header-item {
			&:nth-child(1) {
				flex: 0 0 40px;
				text-align: center;
			}
			&:nth-child(2) {
				flex: 1;
			}
			&:nth-child(3) {
				flex: 0 0 80px;
				text-align: center;
			}
			&:nth-child(4) {
				flex: 0 0 100px;
				text-align: center;
			}
			&:nth-child(5) {
				flex: 0 0 100px;
				text-align: center;
			}
			&:nth-child(6) {
				flex: 0 0 60px;
				text-align: center;
				line-height: 14px;
				.el-icon {
				  font-size: 24px;
				  line-height: 24px;
				}
			}
		}
	}

	.channel-body {
		padding: 0 10px;

		.channel-row {
			display: flex;
			align-items: center;
			padding: 10px 0;
			border-bottom: 1px solid #ebeef5;

			.body-item {
				&:nth-child(1) {
					flex: 0 0 40px;
					text-align: center;
				}
				&:nth-child(2) {
					flex: 1;
					padding-right: 10px;
				}
				&:nth-child(3) {
					flex: 0 0 80px;
					padding-right: 10px;
				}
				&:nth-child(4) {
					flex: 0 0 100px;
					padding-right: 10px;
				}
				&:nth-child(5) {
					flex: 0 0 100px;
					padding-right: 10px;
				}
				&:nth-child(6) {
					flex: 0 0 60px;
					text-align: center;
				}
			}

			&:last-child {
				border-bottom: none;
			}
		}
	}

	.channel-footer {
		width: 100%;
		padding: 10px;
		display: flex;
		justify-content: flex-end;
	}
}
</style>